package top.lingkang.finalgateway.admin.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Assert;
import org.noear.snack.ONode;
import org.noear.solon.annotation.Controller;
import org.noear.solon.annotation.Inject;
import org.noear.solon.annotation.Mapping;
import org.noear.solon.core.handle.MethodType;
import top.lingkang.finalgateway.FinalGateway;
import top.lingkang.finalgateway.admin.dto.ResponseResult;
import top.lingkang.finalgateway.admin.dto.ResponseResultPage;
import top.lingkang.finalgateway.admin.entity.AccessLogEntity;
import top.lingkang.finalgateway.admin.mapper.AccessLogMapper;
import top.lingkang.finalgateway.admin.param.AccessLogParam;
import top.lingkang.finalvalidated.core.ValidObject;
import top.lingkang.mm.page.PageHelper;
import top.lingkang.mm.page.PageInfo;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @author lingkang
 * Created by 2024/5/18
 */
@Controller
@Mapping("/api/accessLog")
public class AccessLogController {
    @Inject
    private AccessLogMapper accessLogMapper;
    @Inject("${admin.password}")
    private String password;

    @Mapping(value = "/list", method = MethodType.GET)
    public Object accessLog(@ValidObject AccessLogParam param) {
        PageHelper.startPage(param.getPage(), param.getSize());
        List<AccessLogEntity> list = accessLogMapper.list(param);
        PageInfo page = PageHelper.getPage();
        return new ResponseResultPage<>().setData(list)
                .setPage(param.getPage())
                .setSize(param.getSize())
                .setTotal(page.getTotal());
    }

    @Mapping(value = "/get", method = MethodType.GET)
    public Object get(String id) {
        Assert.notBlank(id, "id不能为空");
        AccessLogEntity entity = accessLogMapper.selectById(id);
        return new ResponseResult<>(entity);
    }

    @Mapping(value = "/clear", method = MethodType.POST)
    public Object clear(String password) {
        Assert.notBlank(password, "密码不能为空");
        Assert.isTrue(this.password.equals(password), "密码错误");
        File file = new File(FinalGateway.dir + File.separator + "back" + File.separator +
                "access_log_" + System.currentTimeMillis() + ".txt");
        if (!file.getParentFile().exists())
            file.getParentFile().mkdirs();
        while (true) {
            PageHelper.startPage(1, 256);
            List<AccessLogEntity> list = accessLogMapper.selectAll();
            if (list.isEmpty())
                break;
            // 删除
            List<String> txt = new ArrayList<>(list.size());
            List<String> ids = new ArrayList<>(list.size());
            list.forEach(e -> {
                ids.add(e.getId());
                txt.add(ONode.load(e).toJson());
            });
            // 写入文件
            FileUtil.appendUtf8Lines(txt, file);
            accessLogMapper.deleteIn(ids);
        }
        return new ResponseResult<>().ok("清理成功");
    }
}
